<template>
  <el-container style="height: 100%;">
    <el-main>
      <div style="display: flex">
        <div style="flex: 1;margin-right: 10px;" v-for="(contrast, index) in contrastProductTable">
          <el-form ref="form" label-width="80px">
            <el-form-item label="比价单">
              {{contrast.orderCode}}
            </el-form-item>
            <el-form-item label="厂家">
              {{contrast.manufacturerName}}
            </el-form-item>
            <el-form-item label="总价">
              {{contrast.allPrice}}
            </el-form-item>
            <el-form-item label="含税总价">
              {{contrast.hsAllPrice}}
            </el-form-item>
          </el-form>
          <h1>商品信息</h1>
          <el-table :ref="'productTable' + index" :data="contrast.products" @select-all="handleComparisonProductAllSelection(index)" @select="handleComparisonProductSelectionChange">
            <el-table-column type="selection" width="55" align="center" :selectable="handelIsSelect"/>
            <el-table-column label="产品编码" align="center" prop="productCode" :show-overflow-tooltip="true"/>
            <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
            <el-table-column label="计数单位" align="center" prop="unitName" />
            <el-table-column label="商品数量" align="center" prop="productNum" />
            <el-table-column label="商品单价" align="center" prop="oldOnlyPrice" />
            <el-table-column label="商品总价" align="center" prop="oldAllPrice" />
          </el-table>
        </div>
      </div>
    </el-main>
    <el-footer style="padding-top: 15px;height: calc(50% - 15px)">
      <el-form :model="form" :rules="rules" ref="form" size="small" :inline="true" label-width="100px">
        <el-form-item label="利润比例" prop="ratio">
          <el-input
            v-model="form.ratio"
            placeholder="请输入利润比例"
            clearable
          />
        </el-form-item>
        <el-form-item label="报价有效期" prop="valid">
          <el-date-picker clearable
                          v-model="form.valid"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :picker-options="pickerOptions"
                          placeholder="请选择有效期" style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSetting">设置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleSelectedProductDelete"
          >删除</el-button>
        </el-col>
      </el-row>
      <el-table :data="selectedProductList" key="productTable" @selection-change="handleSelectedProductSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品编码" align="center" prop="productCode" :show-overflow-tooltip="true"/>
        <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
        <el-table-column label="计数单位" align="center" prop="unitName" />
        <el-table-column label="商品数量" align="center" prop="productNum" />
        <el-table-column label="商品单价" align="center" prop="showOnlyPrice">
          <template slot-scope="scope">
            <el-input v-model="scope.row.onlyPrice" @blur="handleOnlyPrice(scope.row)" placeholder="请输入商品单价"/>
          </template>
        </el-table-column>
        <el-table-column label="商品总价" align="center" prop="showAllPrice">
          <template slot-scope="scope">
            <el-input v-model="scope.row.allPrice" placeholder="请输入商品单价"/>
          </template>
        </el-table-column>
      </el-table>
    </el-footer>
  </el-container>
</template>

<script>

export default {
  name: "ComparisonProduct",
  dicts: ['wms_product_cc_unit'],
  props: {
    contrastProductTable: {
      type: Array,
      default() {
        return [];
      }
    },
    openFlag: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 选择的ids集合
      ids:[],
      //删除id集合
      delIds: [],
      // 商品code对应表格编号
      idMap: new Map(),
      // 表格编号对应选中商品
      tIndexToIdsMap: new Map(),
      selectedProductList: [],
      form: {
        ratio: null,
        valid: null
      },
      pickerOptions: {
        disabledDate(time) {
          //时间选择框必须大于今天
          return time.getTime() < Date.now() - 8.64e7;
          // 或者 return time.getTime() < Date.now();
        }
      },
      rules:{
        ratio: [
          { pattern: /^(0|[1-9])\d{0,1}(\.\d{1,2})?$/, message: '利润比例只能是数值最大2位整数2位小数', trigger: 'blur' }
        ],
        valid: [
          { required: true, message: "有效期不能为空", trigger: "blur" },
        ]
      },
      // 利润比例
      ratio: 0,
      valid: null
    }
  },
  methods: {
    // 是否可以选择
    handelIsSelect(row, index){
      if (this.ids.includes(row.productCode)) {
        let tableIndex = this.idMap.get(row.productCode)
        return row.tableIndex == tableIndex
      }
      return true
    },
    // 比价单多选框全选事件
    handleComparisonProductAllSelection(tableIndex) {
      //选中的id集合
      let ids = this.tIndexToIdsMap.get(tableIndex)
      //如果当前未存储选中表格id则为全选
      if (!ids || ids.length === 0) {
        let ids = []
        this.contrastProductTable[tableIndex].products.forEach(item => {
          ids.push(item.productCode)
          if (this.ids.indexOf(item.productCode) === -1) {
            this.ids.push(item.productCode)
            this.idMap.set(item.productCode, tableIndex)
            this.selectedProductList.push(item)
            this.alterSelectedProductPrice()
          }
        })
        this.tIndexToIdsMap.set(tableIndex, ids)
      } else {
        //取消全选
        this.tIndexToIdsMap.delete(tableIndex)
        this.contrastProductTable[tableIndex].products.forEach(item => {
          let idsIndex = this.ids.indexOf(item.productCode)
          if (idsIndex > -1) {
            this.idMap.delete(item.productCode)
            this.ids.splice(idsIndex, 1)

            for (let i = 0; i < this.selectedProductList.length; i++) {
              let selItem = this.selectedProductList[i]
              if (selItem.productCode === item.productCode) {
                this.selectedProductList.splice(i,1);
                break
              }
            }
          }
        })
      }
    },
    // 比价单多选框选中数据
    handleComparisonProductSelectionChange(selection,row) {
      // 获取当前表格之前选择的全部id
      let ids = this.tIndexToIdsMap.get(row.tableIndex)
      if (!ids || ids.length === 0){
        ids = []
      }
      if (selection.length > 0) {
        if (ids.length < selection.length) {
          // 选中数据
          selection.forEach(item => {
            if(ids.indexOf(item.productCode) === -1) {
              this.idMap.set(item.productCode, row.tableIndex)
              this.ids.push(item.productCode)
              this.selectedProductList.push(item)
              this.alterSelectedProductPrice()
              ids.push(item.productCode)
            }
          })
        } else {
          let curIds = selection.map(item => item.productCode)
          let delIndex = -1
          // 取消选中数据
          ids.forEach((id, index) => {
            if (curIds.indexOf(id) === -1) {
              delIndex = index
              this.idMap.delete(id)
              this.ids.splice(this.ids.indexOf(id), 1)

              for (let i = 0; i < this.selectedProductList.length; i++) {
                let selItem = this.selectedProductList[i]
                if (selItem.productCode === id) {
                  this.selectedProductList.splice(i,1);
                  break
                }
              }
            }
          })
          ids.splice(delIndex, 1)
        }
        this.tIndexToIdsMap.set(row.tableIndex, ids)
      } else {
        this.tIndexToIdsMap.delete(row.tableIndex)
        this.idMap.delete(row.tableIndex)
        ids.forEach(id => {
          this.ids.splice(this.ids.indexOf(id), 1)
          for (let i = 0; i < this.selectedProductList.length; i++) {
            let selItem = this.selectedProductList[i]
            if (selItem.productCode === id) {
              this.selectedProductList.splice(i,1);
              break
            }
          }
        })
      }
    },
    // 多选框选中数据
    handleSelectedProductSelectionChange(selection) {
      this.delIds = selection.map(item => item.productCode)
    },
    // 删除选择的商品
    handleSelectedProductDelete(){
      this.delIds.forEach(id => {
        let tableIndex = this.idMap.get(id)
        let ids = this.tIndexToIdsMap.get(tableIndex)
        ids.splice(ids.indexOf(id), 1)
        this.tIndexToIdsMap.set(tableIndex, ids)
        this.idMap.delete(id)
        this.ids.splice(this.ids.indexOf(id), 1)
        for(let i=0;i<this.selectedProductList.length;i++){
          if(this.selectedProductList[i].productCode===id){
            this.$refs['productTable' + tableIndex][0].toggleRowSelection(this.selectedProductList[i],false)
            this.selectedProductList.splice(i,1);
            break
          }
        }
      })
    },
    //单价失去焦点事件
    handleOnlyPrice(row){
      if (row.onlyPrice) {
        let reg = /^(0|[1-9])\d{0,6}(\.\d{0,2})?$/
        if (!reg.test(row.onlyPrice)) {
          this.$notify.error("商品单价只能是数值，最大7位整数2位小数")
        } else {
          row.allPrice = (row.productNum * row.onlyPrice).toFixed(2)
        }
      } else {
        row.allPrice = null
      }
    },
    // 设置利润比例
    handleSetting(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.ratio = this.form.ratio;
          this.valid = this.form.valid;
          this.alterSelectedProductPrice()
          this.$message.success("设置成功！")
        }
      });
    },
    alterSelectedProductPrice(){
      this.selectedProductList.forEach((item, index) => {
        if (this.ratio && this.ratio > 0) {
          if (item.onlyPrice != null && item.onlyPrice != undefined) {
            item.onlyPrice = (parseFloat(item.oldOnlyPrice) + parseFloat(this.ratio) * parseFloat(item.oldOnlyPrice)).toFixed(2);
          }
          if (item.allPrice != null && item.allPrice != undefined) {
            item.allPrice = (parseFloat(item.oldAllPrice) + parseFloat(this.ratio) * parseFloat(item.oldAllPrice)).toFixed(2);
          }
        }
      })
    },
    // 获取选择商品列表
    getSelectedProductList(){
      let sign = 0
      let msg = ''
      let products = []
      let orderCodes = []
      let fhz ={
        ratio: null,
        valid: null,
        products: [],
        orderCodes: []
      }
      let reg = /^(0|[1-9])\d{0,6}(\.\d{0,2})?$/
      this.selectedProductList.forEach((item,index) => {
        let contrast = this.contrastProductTable[item.tableIndex]
        if (item.onlyPrice == null || item.onlyPrice == undefined) {
          sign = 1
          msg += "第" + (index + 1) + "行格式异常，商品单价不能为空；"
        } else if (!reg.test(item.onlyPrice)) {
          sign = 1
          msg += "第" + (index+1) +"行格式异常，商品单价只能是数值最大7位整数2位小数；"
        }
        if (item.allPrice == null || item.allPrice == undefined) {
          sign = 1
          msg += "第" + (index + 1) + "行格式异常，商品总价不能为空；"
        } else if (!reg.test(item.allPrice)) {
          sign = 1
          msg += "第" + (index+1) +"行格式异常，商品总价只能是数值最大7位整数2位小数；"
        }

        let obj = {...item}
        obj.priceComparisonOrder = contrast.orderCode
        if (orderCodes.indexOf(contrast.orderCode) === -1) {
          orderCodes.push(contrast.orderCode)
        }
        products.push(obj)
      })
      if (!this.valid) {
        sign = 1
        msg += "有效期不可为空"
      }
      if (sign === 0) {
        fhz.ratio = this.ratio
        fhz.valid = this.valid
        fhz.orderCodes = orderCodes
        fhz.products = products
        return fhz
      } else {
        this.$message.error(msg)
        return {}
      }
    }
  },
  watch:{
    openFlag: {
      handler(nval, oldval){
        if (nval){
          this.ids = []
          this.idMap = new Map()
          this.tIndexToIdsMap = new Map()
          this.delIds = []
          this.form = {
            ratio: null,
            valid: null
          }
          this.ratio = 0
          this.valid = null
          this.selectedProductList = []
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">

</style>
